package com.ds.api;

import com.alibaba.fastjson.JSON;
import com.ds.command.Command;
import com.ds.command.CommandReportStatus;
import com.ds.common.JDSException;
import com.ds.config.ErrorResultModel;
import com.ds.config.ResultModel;
import com.ds.context.JDSActionContext;
import com.ds.enums.db.MethodChinaName;
import com.ds.esb.util.EsbFactory;
import com.ds.iot.GWClientService;
import com.ds.iot.client.CommandWebService;
import com.ds.iot.client.DataWebService;
import com.ds.iot.client.GWAccountWebService;
import com.ds.iot.client.GatewayWebService;
import com.ds.iot.json.NetworkInfo;
import com.ds.iot.json.device.*;
import com.ds.server.comet.AbstractCometHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/Gateway/api")
public class GWWebAPI implements GWClientService {
    private static final Logger logger = LoggerFactory.getLogger(GWWebAPI.class);


    @RequestMapping(method = {RequestMethod.POST}, value = {"/Register"})
    @ResponseBody
    public ResultModel<GatewayRegister> register(@RequestBody Gateway gateway) {
        logger.info("注册网关参数:{}", JSON.toJSONString(gateway));
        ResultModel<GatewayRegister> resultModel = new ResultModel<GatewayRegister>();
        Gateway gatway = null;
        try {

            if (getSceneService() != null) {
                getSceneService().register(gateway).execute();
            }

            if (getVantiqService() != null) {
                getVantiqService().register(gateway).execute();
            }

            gatway = getGWAccountWebService().register(gateway).get();
            resultModel.setData(new GatewayRegister(gatway));

        } catch (Exception e) {
            logger.error("register:注册网关出错,Gateway:" + JSON.toJSONString(gateway), e);
            resultModel = new ErrorResultModel();
            ((ErrorResultModel) resultModel).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) resultModel).setErrdes(e.getMessage());
        }
        return resultModel;
    }

    @MethodChinaName(cname = "网关激活", returnStr = "Activate($Gateway)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/Activate"})
    @ResponseBody
    public ResultModel<GatewayActivate> activate(@RequestBody Gateway gateway) {
        logger.info("激活网关参数:{}", JSON.toJSONString(gateway));
        ResultModel<GatewayActivate> resultModel = new ResultModel<GatewayActivate>();
        Gateway gatway = null;
        try {

            if (getSceneService() != null) {
                getSceneService().activate(gateway).execute();

            }

            if (getVantiqService() != null) {
                getVantiqService().activate(gateway).execute();

            }

            gatway = getGWAccountWebService().activate(gateway).get();
            resultModel.setData(new GatewayActivate(gatway));
        } catch (Exception e) {
            logger.error("activate:激活网关出错,Gateway:" + JSON.toJSONString(gateway), e);
            resultModel = new ErrorResultModel();
            ((ErrorResultModel) resultModel).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) resultModel).setErrdes(e.getMessage());
        }
        return resultModel;
    }

    @MethodChinaName(cname = "告警报告", returnStr = "AlarmReport($SensorData)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/AlarmReport"})
    @ResponseBody
    public ResultModel alarmReport(@RequestBody SensorData sensordata) {
        if (getSceneService() != null) {
            getSceneService().alarmReport(sensordata).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().alarmReport(sensordata).execute();
        }

        getDataWebService().addAlarm(sensordata).execute();

        return new ResultModel();
    }

    @MethodChinaName(cname = "绑定状态报告", returnStr = "BindingStatusReport($CommandReportStatus)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/BindingStatusReport"})
    @ResponseBody
    public ResultModel<Boolean> bindingStatusReport(@RequestBody CommandReportStatus report) {
        if (getSceneService() != null) {
            getSceneService().bindingStatusReport(report).execute();
        }
        if (getVantiqService() != null) {
            getVantiqService().bindingStatusReport(report).execute();
        }
        getCommandWebService().bindingStatusReport(report).execute();
        return new ResultModel();
    }

    @MethodChinaName(cname = "绑定列表报告", returnStr = "BindListReport($BindInfo)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/BindListReport"})
    @ResponseBody
    @Override
    public ResultModel<Boolean> bindListReport(BindInfo bindInfo) {
        // HttpServletRequest request= ((ServletRequestAttributes)
        // RequestContextHolder.getRequestAttributes()).getRequest();
        // BufferedReader br;
        // try {
        // br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
        // String line = null;
        // StringBuilder sb = new StringBuilder();
        // while ((line = br.readLine()) != null) {
        // sb.append(line);
        // }
        // String json=sb.toString();
        // logger.info("paramsJson="+sb.toString());
        // bindInfo= JSONObject.parseObject(json, BindInfo.class);
        //
        // getCommandWebService().bindListReport(bindInfo).execute();
        //
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

        return new ResultModel();
    }

    @MethodChinaName(cname = "修改WIFI网络配置", returnStr = "ChangeNetworkResponse($NetworkInfo)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/ChangeNetworkResponse"})
    @ResponseBody
    public ResultModel<NetworkInfo> changeNetworkResponse(@RequestBody NetworkInfo networkInfo) {
        if (getSceneService() != null) {
            getSceneService().changeNetworkResponse(networkInfo).execute();
        }
        if (getVantiqService() != null) {
            getVantiqService().changeNetworkResponse(networkInfo).execute();
        }
        getGatewayWebService().changeNetworkResponse(networkInfo).execute();
        return new ResultModel();
    }

    @MethodChinaName(cname = "场景模式列表报告", returnStr = "ModeListReport($SenceMode)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/ModeListReport"})
    @ResponseBody
    public ResultModel<Boolean> modeListReport(@RequestBody SenceMode mode) {
        if (getSceneService() != null) {
            getSceneService().modeListReport(mode).execute();
        }
        if (getVantiqService() != null) {
            getVantiqService().modeListReport(mode).execute();
        }
        getCommandWebService().modeListReport(mode).execute();
        return new ResultModel();
    }

    @MethodChinaName(cname = "命令执行状态报告", returnStr = "CommandReport($CommandReportStatus)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/CommandReport"})
    @ResponseBody
    public ResultModel<Boolean> commandReport(@RequestBody CommandReportStatus commandReportStatus) {

        String commandId = commandReportStatus.getCommandId();

        // 心跳拦截
        if (commandId.startsWith("Herat")) {
            AbstractCometHandle.getCheckHeart().put(commandReportStatus.getCommandId(), System.currentTimeMillis());
            return new ResultModel();

        } else {
            if (getSceneService() != null) {
                getSceneService().commandReport(commandReportStatus).execute();
            }
            if (getVantiqService() != null) {
                getVantiqService().commandReport(commandReportStatus).execute();
            }
            getCommandWebService().commandReport(commandReportStatus);
            return new ResultModel<Boolean>();
            // return getCommandWebService().commandReport(commandReportStatus);
        }

    }

    @MethodChinaName(cname = "传感器数据报告", returnStr = "DataReport($SensorData)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/DataReport"})
    @ResponseBody
    public ResultModel<Boolean> dataReport(@RequestBody SensorData sensordata) {
        if (getSceneService() != null) {
            getSceneService().dataReport(sensordata).execute();
        }
        if (getVantiqService() != null) {
            getVantiqService().dataReport(sensordata).execute();
        }
        getDataWebService().addData(sensordata).execute();
        return new ResultModel<Boolean>();
    }

    @MethodChinaName(cname = "查找传感器", returnStr = "FindSensor($SensorListInfo)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/FindSensor"})
    @ResponseBody
    public ResultModel<Boolean> findSensor(@RequestBody SensorListInfo sensorList) {
        if (getSceneService() != null) {
            getSceneService().findSensor(sensorList).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().findSensor(sensorList).execute();
        }
        getGatewayWebService().addSensors(sensorList.getSensors()).execute();
        return new ResultModel<Boolean>();
    }

    @MethodChinaName(cname = "网关错误报告", returnStr = "GatewayErrorReport($GatewayErrorReport)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/GatewayErrorReport"})
    @ResponseBody
    public ResultModel<Map<String, List<Command>>> gatewayErrorReport(@RequestBody GatewayErrorReport errorPort) {

        ResultModel<Map<String, List<Command>>> userStatusInfo = new ResultModel<Map<String, List<Command>>>();

        try {

            if (getVantiqService() != null) {
                getVantiqService().gatewayErrorReport(errorPort).execute();
            }

            if (getSceneService() != null) {
                getSceneService().gatewayErrorReport(errorPort);
            }

            List<Command> commandList = getGWAccountWebService().gatewayErrorReport(errorPort).get();
            userStatusInfo = new ResultModel();
            Map map = new HashMap();
            map.put("commandList", commandList);
            ((ResultModel) userStatusInfo).setData(map);
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
            logger.error("gatewayErrorReport:出错,GatewayErrorReport1:" + JSON.toJSONString(errorPort), e);

        } catch (ExecutionException e) {
            logger.error("gatewayErrorReport:出错,GatewayErrorReport2:" + JSON.toJSONString(errorPort), e);
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;

    }

    @MethodChinaName(cname = "网关在线", returnStr = "GatewayOnLine($Gateway)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/GatewayOnLine"})
    @ResponseBody
    public ResultModel<Boolean> gatewayOnLine(@RequestBody Gateway gateway) {

        if (getSceneService() != null) {
            getSceneService().gatewayOnLine(gateway).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().gatewayOnLine(gateway).execute();
        }

        getGatewayWebService().gatewayOnLine(gateway);
        return new ResultModel();
    }

    @MethodChinaName(cname = "网关下线", returnStr = "GatewayOffLine($Gateway)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/GatewayOffLine"})
    @ResponseBody
    public ResultModel<Boolean> gatewayOffLine(@RequestBody Gateway gateway) {

        if (getSceneService() != null) {
            getSceneService().gatewayOffLine(gateway).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().gatewayOffLine(gateway).execute();
        }

        getGatewayWebService().gatewayOffLine(gateway);
        return new ResultModel();
    }

    @MethodChinaName(cname = "登录", returnStr = "Login($GWUser)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/Login"})
    @ResponseBody
    public ResultModel<GWUser> login(@RequestBody GWUser userInfo) {
        JDSActionContext.getActionContext().getContext().clear();

        return getGWAccountWebService().login(userInfo);
    }

    @MethodChinaName(cname = "注销", returnStr = "Logout()")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/Logout"})
    @ResponseBody
    public ResultModel<Boolean> logout() {

        if (getSceneService() != null) {
            getSceneService().logout().execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().logout().execute();
        }

        getGWAccountWebService().logout();

        return new ResultModel();
    }

    @MethodChinaName(cname = "传感器下线", returnStr = "SensorOffLine($Sensor)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/SensorOffLine"})
    @ResponseBody
    public ResultModel<Boolean> sensorOffLine(@RequestBody Sensor sensor) {

        if (getSceneService() != null) {
            getSceneService().sensorOffLine(sensor).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().sensorOffLine(sensor).execute();
        }

        getGatewayWebService().sensorOffLine(sensor).execute();
        return new ResultModel();
    }

    @MethodChinaName(cname = "传感器在线", returnStr = "SensorOnLine($Sensor)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/SensorOnLine"})
    @ResponseBody
    public ResultModel<Boolean> sensorOnLine(@RequestBody Sensor sensor) {

        if (getSceneService() != null) {
            getSceneService().sensorOnLine(sensor).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().sensorOnLine(sensor).execute();
        }

        getGatewayWebService().sensorOnLine(sensor).execute();
        return new ResultModel();
    }

    @MethodChinaName(cname = "传感器列表报告", returnStr = "SensorReport($SensorListInfo)")

    @RequestMapping(method = {RequestMethod.POST}, value = {"/SensorReport"})
    @ResponseBody
    public ResultModel<Boolean> sensorReport(@RequestBody SensorListInfo sensorList) {

        if (getSceneService() != null) {
            getSceneService().sensorReport(sensorList).execute();
        }

        if (getVantiqService() != null) {
            getVantiqService().sensorReport(sensorList).execute();
        }
        ResultModel model = new ResultModel();

        getGatewayWebService().syncSensor(sensorList.getSensors()).execute();

        return new ResultModel();
    }

    DataWebService getDataWebService() {
        return (DataWebService) EsbFactory.par("$DataWebService");
    }

    CommandWebService getCommandWebService() {
        return (CommandWebService) EsbFactory.par("$CommandWebService");
    }

    GatewayWebService getGatewayWebService() {

        return (GatewayWebService) EsbFactory.par("$GatewayWebService");
    }

    GWAccountWebService getGWAccountWebService() {
        return (GWAccountWebService) EsbFactory.par("$GWAccountWebService");
    }

    GWClientService getSceneService() {

        return (GWClientService) JDSActionContext.getActionContext().Par("$GWSceneService");
    }

    GWClientService getVantiqService() {
        return null;
        // return (GWClientService) EsbUtil.parExpression("$GWVantiqService");
    }

}
